 /*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /**
 * Project  : EasyAvatar-Android
 * Package  : net.solosky.easyavatar.utils
 * File     : AsyncTaskHelper.java
 * Author   : solosky < solosky772@qq.com >
 * Created  : Nov 13, 2011
 * License  : Apache License 2.0 
 */
package net.solosky.easyavatar.utils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.solosky.easyavatar.utils.AsyncTask.Status;


/**
 *
 * 工具类，管理异步任务，可以控制异步任务的数量和批量终止任务
 *
 * @author solosky <solosky772@qq.com>
 *
 */
public class TaskHelper {
	/**任务列表*/
	private List<AsyncTask> mTaskList;
	public TaskHelper(){
		mTaskList = new ArrayList<AsyncTask>();
	}
	
	/**
	 * 添加一个任务
	 * 如果当前进行的任务数小于允许同时允许的最大数量，则立即启动，否则等待其他任务完成才继续
	 * @param task
	 */
	public void addAsyncTask(AsyncTask task, Object ... params){
		synchronized (mTaskList) {
			mTaskList.add(task);
		}
	
		task.execute(params);
	}
	
	/**
	 * 取消所有任务
	 */
	public void cancelAllTasks(){
		synchronized (mTaskList) {
			Iterator<AsyncTask> it = mTaskList.iterator();
			while(it.hasNext()){
				AsyncTask task = it.next();
				safeCancelTask(task);
			}
			mTaskList.clear();
		}
	}
	
	/**
	 * 安全的取消一个任务
	 * @param task
	 */
	public static void safeCancelTask( AsyncTask task){
		if(task!=null && !task.isCancelled() &&
				task.getStatus()!=Status.FINISHED){
			task.cancel(true);
		}
	}
}
